<?php

class Jf_Controller_Plugin_Layout extends Jf_Controller_Plugin_Abstract {

    private $_layoutFile = 'layout.phtml';

    private $_layoutPath = '';

    private $_layoutVars = array();

    protected $_enabled = true;

    public function __set ($name, $value) {
        $this -> _layoutVars[$name] = $value;
    }

    public function disableLayout () {
        $this -> _enabled = false;
        return $this;
    }

    public function enableLayout () {
        $this -> _enabled = true;
        return $this;
    }

    public function isEnabled () {
        return $this -> _enabled;
    }

    public function setLayout ($layout) {
        $this -> _layoutFile = $layout;
        return $this;
    }

    public function setLayoutPath ($layoutPath) {
        $this -> _layoutPath = $layoutPath;
        return $this;
    }

    public function dispatchLoopShutdown (Jf_Controller_Request_Abstract $request, Jf_Controller_Response_Abstract $response) {
        $this -> enableLayout ();
    }

    public function postDispatch (Jf_Controller_Request_Abstract $request, Jf_Controller_Response_Abstract $response) {
        if ( ! $this -> isEnabled () || $request -> isPost ()) {
            return;
        }
        $dispatcher = Jf_Controller_Dispatcher::getInstance ();
        if ( ! $dispatcher -> isEnbleView ()) {
            return;
        }
        $view = Jf_View::getView ();
        $view -> setScriptPath ($this -> _layoutPath);
        $view -> content = $response -> getBody ();
        $view -> layout = $this -> _layoutVars;
        $response -> setBody ($view -> render ($this -> _layoutFile));
    }

}